package com.yjb.tenet.boot.system.application.manager;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yjb.tenet.boot.common.constants.GlobalConstants;
import com.yjb.tenet.boot.common.enums.CommonStatusEnum;
import com.yjb.tenet.boot.common.pojo.PageResult;
import com.yjb.tenet.boot.framework.mybatis.plus.core.util.MyBatisUtils;
import com.yjb.tenet.boot.system.application.convert.SysLoginLogConvert;
import com.yjb.tenet.boot.system.application.service.SysLoginLogService;
import com.yjb.tenet.boot.system.domain.dto.SysLoginLogDTO;
import com.yjb.tenet.boot.system.domain.entity.SysLoginLog;
import com.yjb.tenet.boot.system.domain.query.SysLoginLogPageQuery;
import com.yjb.tenet.boot.system.infrastructure.enums.LoginResultEnum;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @description 
 * @author yinjinbiao
 * @create 2023/3/14 15:16
 * @version 1.0
 */
@Component
public class SysLoginLogManager {

	@Resource
	private SysLoginLogService sysLoginLogService;

	public PageResult<SysLoginLogDTO> page(SysLoginLogPageQuery query){
		IPage<SysLoginLog> page = MyBatisUtils.buildPage(query);
		sysLoginLogService.page(page, Wrappers.<SysLoginLog>query().lambda()
				.eq(SysLoginLog::getDeleted, GlobalConstants.NOT_DELETED)
				.like(StrUtil.isNotBlank(query.getUserIp()), SysLoginLog::getUserIp, query.getUserIp())
				.like(StrUtil.isNotBlank(query.getUsername()), SysLoginLog::getUsername, query.getUsername())
				.eq(StrUtil.equals(CommonStatusEnum.ENABLE.getValue(),  query.getStatus()), SysLoginLog::getResult, LoginResultEnum.SUCCESS.getValue())
				.ne(StrUtil.equals(CommonStatusEnum.DISABLE.getValue(),  query.getStatus()), SysLoginLog::getResult, LoginResultEnum.SUCCESS.getValue())
				.ge(ObjectUtil.isNotEmpty(query.getCreateTimeStart()), SysLoginLog::getCreateTime, query.getCreateTimeStart())
				.le(ObjectUtil.isNotEmpty(query.getCreateTimeEnd()), SysLoginLog::getCreateTime, query.getCreateTimeEnd())
				.orderByDesc(SysLoginLog::getId)
		);
		return new PageResult<SysLoginLogDTO>(SysLoginLogConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());
	}
}
